<?php
/**
 * Created by PhpStorm.
 * User: dongr
 * Date: 2018/5/3
 * Time: 21:08
 */

namespace console\controllers;


use Swoole\Server;
use yii\console\Controller;

class SwooleServerController extends Controller
{
    public function actionRun()
    {
        $server = new Server('0.0.0.0', '9501');
        $server->on('connect', [$this, 'onConnect']);
        $server->on('receive', [$this, 'onReceive']);
        $server->on('close', [$this, 'onClose']);
        $server->start();
    }

    public function onConnect(Server $server, $fd, $reactorId)
    {
        echo "connection open: {$fd}\n";
    }

    public function onReceive(Server $server, $fd, $reactorId, $data)
    {
        // 向客户端发送数据
        $server->send($fd, "Swoole: {$data}");
        // 关闭客户端
        $server->close($fd);
    }

    public function onClose(Server $server, $fd)
    {
        echo "connection close: {$fd}\n";
    }
}